
#include "stm32lib/stm32f10x_iwdg.h"

#include "timeout.h"

Timeout::Timeout(void)
{
  default_time = 0;
  odd_even_cycle = false;
  timeout_odd_even = false;
  previous_now = Rtc::now();
}

Timeout::Timeout(int milliseconds)
{
  default_time = milliseconds;
}

RtcTimestamp Timeout::now(void)
{
  RtcTimestamp local_now;
  local_now = Rtc::now();
  if (local_now < previous_now) {
    odd_even_cycle = !odd_even_cycle;
  }
  previous_now = local_now;
  return previous_now;
}

void Timeout::setDefaultTime(int milliseconds)
{
  default_time = milliseconds;
}

void Timeout::restart(void)
{
  RtcTimestamp local_now;
  local_now = now();
  timeout = RtcTimestamp(local_now + default_time);
  if (timeout >= local_now) {
    timeout_odd_even = odd_even_cycle;
  } else {
    timeout_odd_even = !odd_even_cycle;
  }
}

void Timeout::restart(int milliseconds)
{
  setDefaultTime(milliseconds);
  restart();
}

bool Timeout::timedOut(void)
{
  // Clear watchdog
  //IWDG_ReloadCounter();
  if ((now() > timeout) && (timeout_odd_even == odd_even_cycle))
  {
    return true;
  } else {
    return false;
  }
}

bool Timeout::notTimedOut(void)
{
  return !timedOut();
}

int Timeout::timeToGo(void)
{
  return timeout - now();
}
